<template>
  <div style="padding: 0px 15px;" class="overflowY">
    <div class="searchGroup_list" style="padding: 0px 0px 10px 0px;margin: 0px 0px 0px 0px;">
      <el-row :gutter="20">
        <el-col :sm="6" :xl="4">
          <div class="searchBoxList">
            <el-row>
              <el-col :span="10">
                <span class="searchListName">流程名称: </span>
              </el-col>
              <el-col :span="14">
                <el-input size="small" v-model="queryCondition.procName" placeholder="请输入流程名称" :clearable="true"></el-input>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <el-col :sm="6" :xl="4">
          <div class="searchBoxList">
            <el-row>
              <el-col :span="10">
                <span class="searchListName">流程版本: </span>
              </el-col>
              <el-col :span="14">
                <el-input size="small" v-model="queryCondition.procVersion" placeholder="请输入流程版本" :clearable="true"></el-input>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <el-col :sm="6" :xl="4">
          <div class="searchBoxList">
            <el-row>
              <el-col :span="10">
                <span class="searchListName">激活状态: </span>
              </el-col>
              <el-col :span="14">
                <el-select v-model="queryCondition.isActiveVersion" placeholder="请选择激活状态" size="small" :clearable="true">
                  <el-option
                    v-for="item in activeVersionOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <el-col :sm="6" :xl="4">
          <div class="searchBoxList">
            <el-row>
              <el-col :span="8">
                <span class="searchListName">流程ID: </span>
              </el-col>
              <el-col :span="16">
                <el-input size="small" v-model="queryCondition.procId" placeholder="请输入流程ID" :clearable="true"></el-input>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col>
          <div style="display: inline-block;text-align: left;width: 100%;padding-top: 11px;">
            <el-button type="primary" size="mini" class="size" @click="toAddRecord"><i class="el-icon-plus el-icon--left"></i>新增</el-button>
            <el-button type="primary" size="mini" class="size" @click="toEditRecord"><i class="el-icon-edit el-icon--left"></i>编辑</el-button>
            <el-button type="primary" size="mini" class="size" @click="deleteRecord"><i class="el-icon-delete el-icon--left"></i>删除</el-button>
            <el-button type="primary" size="mini" class="size" @click="activeRecord"><i class="el-icon-check el-icon--left"></i>激活</el-button>
            <el-button type="primary" size="mini" class="size" @click="toCopyProcess"><i class="el-icon-document el-icon--left"></i>复制</el-button>
            <el-button type="primary" size="mini" class="size" @click="exportProcess"><i class="el-icon-download el-icon--left"></i>导出</el-button>
            <el-button type="primary" size="mini" class="size" @click="toImportProcess">导入<i class="el-icon-upload el-icon--right"></i></el-button>
            <el-button type="primary" size="mini" class="size" @click="toChangeBizCategory"><i class="el-icon-setting el-icon--left"></i>更改分类</el-button>
            <el-button type="primary" size="mini" class="size" icon="el-icon-search" @click="fetchData">搜索</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

    <div style="position: relative;border: 1px solid #ccc;padding:0px 0px 54px 0px;margin:0px 0px 0px 0px;position: relative;">
      <el-table
        ref="singleTable"
        :data="tableData"
        tooltip-effect="dark"
        @row-contextmenu="rowContextmenu"
        @cell-dblclick="cellClick"
        @row-click="rowClick"
        @sort-change="sortChange"
        @current-change="handleCurrentChange"
        :highlight-current-row="true"
        height="340"
        style="width: 100%">
        <el-table-column
          width="50"
          align="center"
          label="序号">
          <template slot-scope="scope">
            <span>{{scope.$index + (pagingArgs.currentPageNo - 1) * 10 + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column
          width="200"
          prop="procName"
          align="left"
          sortable="custom"
          :show-overflow-tooltip="true"
          label="流程名称">
        </el-table-column>
        <el-table-column
          width="80"
          prop="procVersion"
          align="center"
          label="流程版本">
        </el-table-column>
        <el-table-column
          width="120"
          prop="isActiveVersion"
          align="center"
          sortable="custom"
          label="激活状态">
        </el-table-column>
        <el-table-column
          width="150"
          prop="buildTime"
          align="center"
          sortable="custom"
          :show-overflow-tooltip="true"
          label="创建时间">
        </el-table-column>
        <el-table-column
          width="150"
          prop="modifiedTime"
          align="center"
          sortable="custom"
          :show-overflow-tooltip="true"
          label="修改时间">
        </el-table-column>
        <el-table-column
          width="120"
          prop="procCategoryName"
          align="center"
          sortable="custom"
          label="流程分类">
        </el-table-column>
        <el-table-column
          width="200"
          prop="procDesc"
          align="center"
          :show-overflow-tooltip="true"
          label="流程描述">
        </el-table-column>
        <el-table-column
          width="250"
          prop="procId"
          align="center"
          :show-overflow-tooltip="true"
          label="流程ID">
        </el-table-column>
      </el-table>
      <div style="position: absolute;bottom:0;left: 10px;">
        <paging :size-change="pageSizeChange"
                :current-change="pagingQuery"
                :page-sizes="pageSizes"
                :total-num="pagingArgs.totalCount">
        </paging>
      </div>
    </div>
    <el-dialog title="流程分类选择" :visible.sync="copyProcessIsDisplay" :close-on-click-modal="false" :destroy-on-close="true"
               v-if="copyProcessIsDisplay" top="30px" custom-class="myDialog">
      <wf-biz-category-select @setBizCategory="copyProcess" :asyncData="copyProcessAsyncData"></wf-biz-category-select>
    </el-dialog>
    <el-dialog title="流程分类选择" :visible.sync="changeBizCategoryIsDisplay" :close-on-click-modal="false" :destroy-on-close="true"
               v-if="changeBizCategoryIsDisplay" top="30px" custom-class="myDialog">
      <wf-biz-category-select @setBizCategory="changeBizCategory" :asyncData="changeBizCategoryAsyncData"></wf-biz-category-select>
    </el-dialog>
    <el-dialog title="流程导入" :visible.sync="importProcessIsDisplay" :close-on-click-modal="false" :destroy-on-close="true"
               v-if="importProcessIsDisplay" top="30px" custom-class="myDialog">
      <wf-process-import :bizCateId="bizCateId" :bizCateName="bizCateName" @doComplete="completeImport"></wf-process-import>
    </el-dialog>

    <el-dialog v-if="dialogComplete" id="completeDialog" title="新增流程" :visible.sync="dialogComplete" :fullscreen="true" @close="closeDialog">
      <div id="completeDiv" >
        <iframe id="aaa" ref="iframeComplete" frameborder="0" :src="iframeUrl" height="700" width="100%"></iframe>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import paging from '@/components/demoAssembly/paging' // 分页
import { wfBizCategorySelect, wfProcessImport } from '@/views/workFlowManage/workFlowDefine/components'
import { getToken } from '@/utils/auth'
export default {
  name: 'wfProcessMain',
  data() {
    return {
      dialogComplete: false,
      completeTask: process.env.WORKFLOW_INDEX,
      iframeUrl: '',
      baseApi: process.env.BASE_API + '/workflow',
      pageSizes: [10, 20, 30, 40],
      // 分页参数
      pagingArgs: {
        currentPageNo: 1,
        totalCount: 0
      },
      tableData: [], // 列表数据
      queryArgs: {
        sort: [
          {
            property: 'procName',
            direction: 'ASC'
          },
          {
            property: 'modifiedTime',
            direction: 'DESC'
          }
        ],
        rowBounds: {
          offset: 0,
          limit: 10
        },
        bizCateId: ''
      },
      // 查询参数
      queryCondition: {
        procName: '',
        procVersion: '',
        isActiveVersion: '',
        procId: ''
      },
      activeVersionOptions: [ // 下拉框选项
        {
          value: '0',
          label: '未激活'
        },
        {
          value: '1',
          label: '已激活'
        }
      ],
      selectRecord: null,
      copyProcessIsDisplay: false,
      copyProcessAsyncData: 0,
      changeBizCategoryIsDisplay: false,
      changeBizCategoryAsyncData: 0,
      importProcessIsDisplay: false
    }
  },
  props: ['bizCateId', 'bizCateName'],
  watch: {
    bizCateId() { // 普通的watch监听通的watch监听
      this.selectRecord = null
      this.clearQueryConditions()
      this.fetchData()
    }
  },
  computed: {

  },
  filters: {

  },
  components: {
    paging,
    wfBizCategorySelect,
    wfProcessImport
  },
  /**
   * 组件创建完成后，查询列表数据
   */
  created() {

  },
  mounted() {
    this.fetchData()
  },
  methods: {
    rowClick() {
      // 行单击事件
    },
    cellClick(row, column, cell, event) {
      // 列单击事件
    },
    rowContextmenu(row, column, e) {
      // 右键菜单
      window.event.returnValue = false
    },
    pageSizeChange(val) {
      this.queryArgs.rowBounds.limit = val
      this.queryArgs.rowBounds.offset = 0
      this.pagingArgs.currentPageNo = 1
      this.fetchData()
    },
    sortChange(col) {
      //
      if (col.prop) {
        let tempDirection = 'ASC'
        if (col.order === 'descending') {
          tempDirection = 'DESC'
        }
        const sort = {
          property: col.prop,
          direction: tempDirection
        }
        this.queryArgs.sort = []
        this.queryArgs.sort.push(sort)
        this.fetchData()
      }
    },
    pagingQuery(val) { // 分页
      this.queryArgs.rowBounds.offset = (val - 1) * 10
      this.pagingArgs.currentPageNo = val
      this.fetchData()
    },
    buildQueryConditions() {
      let tempQueryCondition = []
      // 流程名称
      if (this.queryCondition.procName != null && this.queryCondition.procName !== '') {
        const queryProcName = {
          property: 'procName',
          value: this.queryCondition.procName,
          type: 'LIKE'
        }
        tempQueryCondition.push(queryProcName)
      }

      // 流程版本
      if (this.queryCondition.procVersion != null && this.queryCondition.procVersion !== '') {
        const queryProcVersion = {
          property: 'procVersion',
          value: this.queryCondition.procVersion,
          type: 'EQ'
        }
        tempQueryCondition.push(queryProcVersion)
      }

      // 是否激活
      if (this.queryCondition.isActiveVersion != null && this.queryCondition.isActiveVersion !== '') {
        const queryIsActiveVersion = {
          property: 'isActiveVersion',
          value: this.queryCondition.isActiveVersion,
          type: 'EQ'
        }
        tempQueryCondition.push(queryIsActiveVersion)
      }

      // 流程ID
      if (this.queryCondition.procId != null && this.queryCondition.procId !== '') {
        const queryProcId = {
          property: 'procId',
          value: this.queryCondition.procId,
          type: 'EQ'
        }
        tempQueryCondition.push(queryProcId)
      }

      return tempQueryCondition
    },
    clearQueryConditions() {
      for (let key in this.queryCondition) {
        this.queryCondition[key] = ''
      }
    },
    fetchData() { // 获取内容
      this.queryArgs.bizCateId = this.bizCateId
      this.queryArgs.condition = this.buildQueryConditions()
      console.log(this.queryArgs)
      this.$store
        .dispatch('WfProcessSelectByCateId', this.queryArgs)
        .then(res => {
          let records = res.data.records
          if (records) {
            records.forEach((item, index) => {
              // 格式化时间
              item.buildTime = this.timeFormat(item.buildTime)
              item.modifiedTime = this.timeFormat(item.modifiedTime)
              let isActiveVersion = item.isActiveVersion
              if (isActiveVersion === 1) {
                item.isActiveVersion = '已激活'
              } else {
                item.isActiveVersion = '未激活'
              }
            })
          }
          this.tableData = records
          this.pagingArgs.totalCount = res.data.count
          this.selectRecord = null
        })
        .catch(() => {

        })
    },
    handleCurrentChange(currentRow, oldCurrentRow) {
      //
      this.selectRecord = currentRow
    },
    closeDialog() {
      this.fetchData()
    },
    toAddRecord() {
      if (this.bizCateId) {
        this.iframeUrl = `${this.completeTask}?bizCateId=${this.bizCateId}&token=${getToken()}`
        this.dialogComplete = true
        // const procId = '7ba6abae75bc4336a51d2ca192cb97f5'
        // const procVersion = '1'
        // this.iframeUrl = `${this.completeTask}?procId=${procId}&procVersion=${procVersion}&token=${getToken()}`
        this.dialogComplete = true
      } else {
        this.$message({
          type: 'warning',
          message: '请选择流程分类！'
        })
      }
    },
    toEditRecord() {
      //
      if (this.selectRecord) {
        const procId = this.selectRecord.procId
        const procVersion = this.selectRecord.procVersion
        this.iframeUrl = `${this.completeTask}?procId=${procId}&procVersion=${procVersion}&token=${getToken()}`
        this.dialogComplete = true
      } else {
        this.$message({
          type: 'warning',
          message: '请选择流程！'
        })
      }
    },
    deleteRecord() {
      if (this.selectRecord) {
        const procId = this.selectRecord.procId
        const procVersion = this.selectRecord.procVersion

        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          let args = {}
          args.procId = procId
          args.procVersion = procVersion
          this.$store.dispatch('WfProcessDelete', args).then(res => {
            this.fetchData()
            this.loading = false
            if (res.success) {
              this.$message({
                type: 'info',
                message: '删除成功！'
              })
            } else {
              this.$message({
                type: 'error',
                message: '删除异常！' + res.message
              })
            }
          }).catch((err) => {
            console.log(err)
            this.$message({
              type: 'warning',
              message: '删除异常！'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        this.$message({
          type: 'warning',
          message: '请选择流程！'
        })
      }
    },
    activeRecord() {
      if (this.selectRecord) {
        const procId = this.selectRecord.procId
        const procVersion = this.selectRecord.procVersion

        this.$confirm('确认激活此流程吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          let args = {}
          args.procId = procId
          args.procVersion = procVersion
          this.$store.dispatch('WfProcessActive', args).then(res => {
            this.fetchData()
            this.loading = false
            if (res.success) {
              this.$message({
                type: 'info',
                message: '激活成功！'
              })
            } else {
              this.$message({
                type: 'error',
                message: '激活异常！' + res.message
              })
            }
          }).catch((err) => {
            console.log(err)
            this.$message({
              type: 'warning',
              message: '激活异常！'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消激活'
          })
        })
      } else {
        this.$message({
          type: 'warning',
          message: '请选择流程！'
        })
      }
    },
    toCopyProcess() {
      //
      if (this.selectRecord) {
        this.copyProcessAsyncData = this.copyProcessAsyncData + 1
        this.copyProcessIsDisplay = true
      } else {
        this.$message({
          type: 'warning',
          message: '请选择流程！'
        })
      }
    },
    copyProcess(args) {
      //
      this.copyProcessIsDisplay = false
      if (this.selectRecord) {
        const procId = this.selectRecord.procId
        const procVersion = this.selectRecord.procVersion
        const bizCateId = args.bizCateId
        this.$confirm('确认复制此流程吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          let args = []
          args.procId = procId
          args.procVersion = procVersion
          args.bizCateId = bizCateId
          this.$store.dispatch('WfProcessCopy', args).then(res => {
            this.fetchData()
            this.loading = false
            if (res.success) {
              this.$message({
                type: 'info',
                message: '复制成功！'
              })
            } else {
              this.$message({
                type: 'error',
                message: '复制异常！' + res.message
              })
            }
          }).catch((err) => {
            console.log(err)
            this.$message({
              type: 'warning',
              message: '复制异常！'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消复制'
          })
        })
      } else {
        this.$message({
          type: 'warning',
          message: '请选择流程！'
        })
      }
    },
    toImportProcess() {
      //
      if (this.bizCateId) {
        this.importProcessIsDisplay = true
      } else {
        this.$message({
          type: 'warning',
          message: '请选择流程分类！'
        })
      }
    },
    completeImport(args) {
      this.importProcessIsDisplay = false
      this.fetchData()
    },
    exportProcess() {
      if (this.selectRecord) {
        const procId = this.selectRecord.procId
        const procVersion = this.selectRecord.procVersion
        // let downloadSourcePath = this.baseApi + '/WfProcess/doExportProcess?processId=' + procId + '&processVersion=' + procVersion
        // let downloadElement = document.createElement('a')
        // downloadElement.target = '_blank'
        // downloadElement.href = downloadSourcePath// 此处可以通过拼接字符串的方式传递参数
        // document.body.appendChild(downloadElement)
        // downloadElement.click() // 点击下载
        // document.body.removeChild(downloadElement) // 下载完成之后移除元素

        let args = {}
        args.procId = procId
        args.procVersion = procVersion
        this.$store.dispatch('WfProcessExport', args)
      } else {
        this.$message({
          type: 'warning',
          message: '请选择流程！'
        })
      }
    },
    toChangeBizCategory() {
      if (this.selectRecord) {
        this.changeBizCategoryIsDisplay = true
        this.changeBizCategoryAsyncData++
      } else {
        this.$message({
          type: 'warning',
          message: '请选择流程！'
        })
      }
    },
    changeBizCategory(args) {
      //
      this.changeBizCategoryIsDisplay = false
      if (this.selectRecord) {
        const procId = this.selectRecord.procId
        const procVersion = this.selectRecord.procVersion
        const bizCateId = args.bizCateId
        this.$confirm('确认更改流程分类吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          let args = []
          args.procId = procId
          args.procVersion = procVersion
          args.bizCateId = bizCateId
          this.$store.dispatch('WfProcessChangeCategory', args).then(res => {
            this.fetchData()
            this.loading = false
            if (res.success) {
              this.$message({
                type: 'info',
                message: '更改成功！'
              })
            } else {
              this.$message({
                type: 'error',
                message: '更改异常！' + res.message
              })
            }
          }).catch((err) => {
            console.log(err)
            this.$message({
              type: 'warning',
              message: '更改异常！'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消更改'
          })
        })
      } else {
        this.$message({
          type: 'warning',
          message: '请选择流程！'
        })
      }
    },

    setDialogDisplay() {
      this.busiTypeDialog.isDisplay = false
    },
    listRefresh() {
      this.fetchData()
      this.busiTypeDialog.isDisplay = false
    },
    timeFormat(time) {
      let tempDate = time
      try {
        if (time && time.length > 8) {
          tempDate = time.substring(0, 4) + '-' + time.substring(4, 6) + '-' + time.substring(6, 8)
          tempDate += ' ' + time.substring(8, 10) + ':' + time.substring(10, 12) + ':' + time.substring(12, 14)
        }
      } catch (e) {
        //
        console.info(e)
      }
      return tempDate
    }
  }
}
</script>
<style scoped>
  .tree-title{
    font-size: 16px;
    padding:10px 10px 10px 20px;
    border-bottom: 1px solid #ccc;
  }
  .size{
    padding:4px;
  }
  .tree-detail{
    padding: 10px 0 80px 15px;
  }
  .notSize .el-table__empty-text{
    display: none;
  }
  .tableBtnBox >>> .el-button.is-circle{
    padding: 8px !important;
  }

  .searchBoxList{
    margin-top: 10px;
  }
  .searchGroup_list .searchListName{
    font-size: 14px;
    color: #333333;
    display: inline-block;
    vertical-align: middle;
    line-height: 32px;
  }
  .searchGroup_list .searchListNameOther{
    font-size: 14px;
    color: #333333;
    display: inline-block;
    vertical-align: middle;
    line-height: 32px;
    text-align: center;
    padding-left: 20%;
    padding-right: 20%;
  }

</style>

